package fr.pud.client.controller.address;

import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import fr.pud.client.i18n.LanguagesConstants;
import fr.pud.client.images.ImagesDatabase;
import fr.pud.client.view.AddAddressesFromCSV;

/**
 * The controller used to load a file which contains a lot of addresses.
 * Apr 8, 2012 - OSE
 * @author Simon Devineau, Adrien Hierry, Leopold Houdin, Pierre Reliquet
 *         Ecole des Mines de Nantes
 *         LoadAddressesFile.java
 */
public class LoadAddressesFile extends AbstractAction {
    /**
     * The serial version UID
     */
    private static final long serialVersionUID = -4826190548845466183L;

    /**
     * The default constructor which sets up the GUI.
     */
    public LoadAddressesFile() {
        this.putValue(NAME, LanguagesConstants.LANGUAGE
                .getString(LanguagesConstants.LOAD_ADDRESSES));
        this.putValue(SMALL_ICON, ImagesDatabase.ADDRESSES);
        this.putValue(SHORT_DESCRIPTION, LanguagesConstants.LANGUAGE
                .getString(LanguagesConstants.LOAD_ADDRESSES_DESCRIPTION));
    }

    /**
     * Opens a file chooser and load the data into the database.
     */
    @Override
    public void actionPerformed(ActionEvent arg0) {
        /*
         * Initialization of the explorer
         */
        JFileChooser explorer;
        File f = new File("");
        explorer = new JFileChooser(f.getAbsolutePath());
        FileFilter filterText = new FileNameExtensionFilter(
                LanguagesConstants.LANGUAGE.getString(LanguagesConstants.FILE)
                        + ": txt", "txt");
        FileFilter filterCsv = new FileNameExtensionFilter(
                LanguagesConstants.LANGUAGE.getString(LanguagesConstants.FILE)
                        + ": csv", "csv");
        explorer.addChoosableFileFilter(filterText);
        explorer.addChoosableFileFilter(filterCsv);
        explorer.setFileSelectionMode(JFileChooser.FILES_ONLY);
        /*
         * Getting the file
         */
        explorer.showDialog(
                null,
                LanguagesConstants.LANGUAGE.getString(LanguagesConstants.OPEN)
                        + " "
                        + LanguagesConstants.LANGUAGE.getString(
                                LanguagesConstants.FILE).toLowerCase()
                        + ": csv "
                        + LanguagesConstants.LANGUAGE
                                .getString(LanguagesConstants.OR) + " txt");
        if (explorer.getSelectedFile() != null) {
            f = explorer.getSelectedFile();
            AddAddressesFromCSV swingWorker = new AddAddressesFromCSV(f);
            swingWorker.execute();
        }
    }
}
